package cl.jpavlich.mpm.services;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;

import de.schlichtherle.truezip.file.TArchiveDetector;
import de.schlichtherle.truezip.file.TFile;

public class MPMFileUtils {

	private static final String REPOSITORY_DIR = "repository";
	private static final String CONFIG_DIR = ".minecraft_package_manager";

	/**
	 * @param dir
	 */
	private static void createIfNotExists(File dir) {
		if (!dir.exists()) {
			if (!dir.mkdirs()) {
				throw new RuntimeException("Cannot create: " + dir.toString());
			}
		}
	}

	public static File getRepositoryDir() {
		File repositoryDir = new File(getConfigDir(), REPOSITORY_DIR);
		createIfNotExists(repositoryDir);
		return repositoryDir;
	}

	/**
	 * Obtains the config Dir (and creates it if it does not exist)
	 * 
	 * @return Credits:
	 *         http://stackoverflow.com/questions/193474/how-to-create-an
	 *         -ini-file-to-store-some-settings-in-java
	 * @throws PropertyException
	 */
	public static File getConfigDir() {
		String userHome = System.getProperty("user.home");
		if (userHome == null) {
			throw new RuntimeException("user.home==null");
		}
		File home = new File(userHome);
		File settingsDirectory = new File(home, CONFIG_DIR);
		createIfNotExists(settingsDirectory);
		return settingsDirectory;
	}

	public static File getTmpDir() {
		String tmpDirName = System.getProperty("java.io.tmpdir");
		if (tmpDirName == null) {
			throw new RuntimeException("Unable to find temporary folder");
		}
		File tmpDir = new File(tmpDirName);
		createIfNotExists(tmpDir);
		return tmpDir;

	}

	public static File unzipAll(String zipFileName, String destFolderName)
			throws IOException {

		TFile zip = new TFile(zipFileName);
		TFile destFolder = new TFile(destFolderName);
		if (!zip.isArchive()) {
			throw new IOException("Invalid mod file");
		} else if (!destFolder.isDirectory()) {
			throw new IOException("Invalid destination folder");
		} else {
			TFile finalFolder = new TFile(destFolder, zip.getName() + "/");
			if (finalFolder.exists()) {
				if (finalFolder.isDirectory()) {
					FileUtils.deleteDirectory(finalFolder);
				} else {
					finalFolder.rm();
				}
				finalFolder = new TFile(destFolder, zip.getName() + "/");
				finalFolder.mkdirs();
			}
			TFile.cp_rp(zip, finalFolder, TArchiveDetector.NULL,
					TArchiveDetector.NULL);
			return finalFolder;

		}
	}

}
